package com.ruoyi.electronicFence.task;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.electronicFence.domain.ReceiveEFData;
import com.ruoyi.electronicFence.domain.TDeviceStatus;
import com.ruoyi.electronicFence.service.ITDeviceStatusService;
import com.ruoyi.electronicFence.service.ITEfAlarmService;
import kong.unirest.HttpResponse;
import kong.unirest.Unirest;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

@Component
//更新设备状态的 定时任务
public class updateEquipmentDeviceStatusScheduler {


    private final ITEfAlarmService iTEfAlarmService;

    private final ITDeviceStatusService iTDeviceStatusService;

    public updateEquipmentDeviceStatusScheduler(ITEfAlarmService iTEfAlarmService,ITDeviceStatusService iTDeviceStatusService) {
        this.iTEfAlarmService = iTEfAlarmService;
        this.iTDeviceStatusService = iTDeviceStatusService;
    }

    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd%20HH:mm:ss");

//    @Scheduled(cron = "${scheduler.updateEquipmentDeviceStatusCron}")
//    @Scheduled(cron = "*/30 * * * * *")
    public void updateEquipmentDeviceStatus() {
        LocalDateTime now = LocalDateTime.now();

        List<TDeviceStatus> tDeviceStatuses = iTDeviceStatusService.selectTDeviceStatusList(new TDeviceStatus());
        for ( TDeviceStatus device :tDeviceStatuses){
            String deviceIp = device.getDeviceIp();
            String deviceId = device.getDeviceId();
            // 构建设备的具体URL
            String urlString = "http://" + deviceIp + ":8080/electronicFence/receive-alarm-data?dataTime=" + now.format(FORMATTER);
            try {
                URL url = new URL(urlString);
                // 发送 GET 请求并获取响应
                try{
                    HttpResponse<String> response = Unirest.get(url.toExternalForm())
                            .header("Content-Type", "application/json")
                            .header("Accept", "*/*")
                            .header("Host", deviceIp)
                            .header("Connection", "keep-alive")
                            .connectTimeout(5000)  // 设置连接超时时间
                            .socketTimeout(5000)   // 设置读取超时时间
                            .asString();
                    if (response.getStatus() == 200) {
                        // 输出设备的状态信息
//                                        System.out.println("Device " + deviceId + " status: " + response.getBody());
                        String body = response.getBody();
                        device.setDeviceStatus("在线");

                    }
                }catch (Exception e){
                    device.setDeviceStatus("离线");

                }





                device.setUpdateTime(now);
                iTDeviceStatusService.updateTDeviceStatus(device);

//            updateDeviceOnlineStatus(response.getStatus(),device);
                // 模拟等待，如果服务器没有立即返回响应，则等待
                Thread.sleep(1000); // 1秒
            }
            catch (InterruptedException | MalformedURLException e) {
                Thread.currentThread().interrupt();
            }

    }

    }
    @Scheduled(cron = "*/30 * * * * *")
    public void checkDeviceStatus() {
        LocalDateTime now = LocalDateTime.now();

        List<TDeviceStatus> tDeviceStatuses = iTDeviceStatusService.selectTDeviceStatusList(new TDeviceStatus());
        for (TDeviceStatus device : tDeviceStatuses) {
            String deviceIp = device.getDeviceIp();
            String deviceId = device.getDeviceId();

            // 使用 ping 命令判断设备是否在线
            boolean isOnline = pingDevice(deviceIp);
            if (isOnline) {
                device.setDeviceStatus("在线");
            } else {
                device.setDeviceStatus("离线");
            }

            device.setUpdateTime(now);
            iTDeviceStatusService.updateTDeviceStatus(device);

            // 模拟等待，如果服务器没有立即返回响应，则等待
            try {
                Thread.sleep(1000); // 1秒
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }

    private boolean pingDevice(String ipAddress) {
        try {
            InetAddress address = InetAddress.getByName(ipAddress);
            return address.isReachable(5000); // 设置超时时间为5000毫秒
        } catch (Exception e) {
            return false;
        }
    }
    /*
    获取设备状态
     */
    @Transactional
    public  String getEquipmentDeviceStatus(){

        List<TDeviceStatus> tDeviceStatuses = iTDeviceStatusService.selectTDeviceStatusList(new TDeviceStatus());
        for (TDeviceStatus tDevice:tDeviceStatuses){
            String deviceIp = tDevice.getDeviceIp();
            String url ="";
            url="http://"+deviceIp+":8080/electronicFence/receive-alarm-data";
            LocalDateTime now = LocalDateTime.now();

            // 定义日期时间格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd%20HH:mm:ss");
            // 格式化时间
            String formattedDateTime = now.format(formatter);
            url=url+"?dataTime="+formattedDateTime;
            System.out.println(url);
            // 发送 GET 请求并获取响应
            HttpResponse<String> response = Unirest.get(url)
                    .header("Content-Type", "application/json")
                    .header("Accept", "*/*")
                    .header("Host", "192.168.3.43:8080")
                    .header("Connection", "keep-alive")
                    .asString();

//    // 输出响应内容和状态码
//        System.out.println("Response status: " + response.getStatus());
//        System.out.println("Response body: " + response.getBody());
            String body = response.getBody(); // 将 JSON 字符串转换为 JSONObject
            JSONObject jsonObject = new JSONObject(body);

            // 将 JSONObject 转换为 Map
            Map<String, Object> map = new JSONObject(body).toMap();
            Map<String, Object> map1 = dataConversion(map);
            Object msg = map.get("Msg");

        }

        return null;
    }

    public AjaxResult dataConversion(Map<String, Object> map ) {
        AjaxResult ajaxResult = new AjaxResult();
        //如果响应成功 则向报警数据存数
        if (map.get("Result").equals("Succeed")){
            //new 接收报警数据对象
            ReceiveEFData receiveEFData = new ReceiveEFData();
            //解析控制器类型
            String controllerStatus = (String)map.get("controllerStatus");
            receiveEFData.setControllerStatus(controllerStatus);
//           if (controllerStatus.equals("1")||controllerStatus.equals("2")){
            //解析时间
            String alarmTime = (String)map.get("alarmTime");
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime alarmDateTime = LocalDateTime.parse(alarmTime, formatter);
            receiveEFData.setAlarmTime(alarmDateTime);
            //解析IP
            String controllerIP = (String)map.get("controllerIP");
            receiveEFData.setControllerIP(controllerIP);


            String equipmentStatus = (String)map.get("equipmentStatus");
            receiveEFData.setEquipmentStatus(equipmentStatus);

            String pictureUrl = (String)map.get("pictureUrl");
            receiveEFData.setPictureUrl(pictureUrl);

            // 获取值
            Object value = map.get("alarmType");
            String[] alarmType = new String[0];
            if (value != null && value instanceof String[]) {
                alarmType = (String[]) value;
            }
            receiveEFData.setAlarmType(alarmType);

            Map<String, List<Map<String,Object>>> personCardInfoMap = (Map<String,List<Map<String,Object>>>)map.get("personCardInfo");
            receiveEFData.setPersonCardInfoMap(personCardInfoMap);
            int i = iTEfAlarmService.InboundDataOftAlarm(receiveEFData);
            if (i>0){
                ajaxResult.isSuccess();
                ajaxResult.put("code",200);
                ajaxResult.put("msg","入库成功");
            }
//           }

        }else {
            ajaxResult.isError();
            ajaxResult.put("code",500);
            ajaxResult.put("msg","入库失败");
        }
        return ajaxResult;
    }
}
